package com.coderside.fragment.thread.ABCD;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;

class Worker extends Thread {

	private Queue[] queue;
	private FileOutputStream[] fos;
	private String name;
	private CountDownLatch cdl;
	private int circleNum;
	private CountDownLatch start;

	public Worker(Queue[] queue, String name, CountDownLatch cdl,
			CountDownLatch start, FileOutputStream[] fos, int circleNum) {
		this.queue = queue;
		this.name = name;
		this.cdl = cdl;
		this.start = start;
		this.fos = fos;
		this.circleNum = circleNum;
	}

	public void run() {
		try {
			start.await();// 等待主线程一声令下,所有的子线程均唤醒开始工作
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		int maxNum = 0;
		for (;;) {

			for (int i = 1; i < queue.length; i++) {
				synchronized (fos[i - 1]) {
					if (((String) queue[i].peek()).equals(name)) {
						Object o = queue[i].poll();
						try {
							fos[i - 1].write(name.getBytes());
						} catch (IOException e) {
							e.printStackTrace();
						}
						queue[i].add(o);
					}
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();

					}
				}
			}
			maxNum++;
			cdl.countDown();
			if (maxNum > circleNum) {
				break;
			}

		}
	}
}